import type { KnowledgeDetail } from '@/types/knowledge';

/**
 * Java核心API知识点数据
 */
export const coreKnowledge : KnowledgeDetail[] = [
	{
		id: 11,
		title: 'String类',
		description: 'String是Java中最常用的类，理解String的不可变性、常量池、常用方法是Java编程的基础。',
		icon: '📝',
		categoryId: 'core',
		categoryName: 'Java核心API',
		categoryIcon: '🔧',
		difficulty: '重要',
		color: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #16a085 0%, #138d75 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #f39c12 0%, #e67e22 100%)',
		keyPoints: [
			{
				point: 'String是不可变类(immutable)，一旦创建不能修改，任何修改操作都会创建新对象。',
				code: `public class StringImmutable {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = str1;  // str1和str2指向同一对象
        
        str1 = str1 + " World";  // 创建新对象，str1指向新对象
        
        System.out.println(str1);  // "Hello World"
        System.out.println(str2);  // "Hello"（原对象未改变）
        
        // String不可变的原因
        String s = "abc";
        // s.charAt(0) = 'd';  // 错误！没有这种方法
        
        // 反射也无法修改（value是final的）
        // String内部：private final char[] value;
    }
}`
			},
			{
				point: '字符串常量池(String Pool)存储字符串字面量，相同内容的字符串共享同一对象，节省内存。',
				code: `public class StringPool {
    public static void main(String[] args) {
        // 字面量，存储在常量池
        String s1 = "Hello";
        String s2 = "Hello";
        System.out.println(s1 == s2);  // true（同一对象）
        
        // new创建，存储在堆中
        String s3 = new String("Hello");
        String s4 = new String("Hello");
        System.out.println(s3 == s4);  // false（不同对象）
        System.out.println(s1 == s3);  // false
        
        // intern()方法：将字符串放入常量池
        String s5 = s3.intern();
        System.out.println(s1 == s5);  // true
        
        // 编译期优化
        String s6 = "He" + "llo";  // 编译期合并
        System.out.println(s1 == s6);  // true
    }
}`
			},
			{
				point: 'String常用方法：长度、查找、比较、截取、替换、分割、大小写转换等，需要注意返回新对象。',
				code: `public class StringMethods {
    public static void main(String[] args) {
        String str = "Hello World";
        
        // 长度和字符访问
        int len = str.length();           // 11
        char ch = str.charAt(0);          // 'H'
        
        // 查找
        int index1 = str.indexOf('o');    // 4（第一次出现）
        int index2 = str.lastIndexOf('o'); // 7（最后一次）
        boolean contains = str.contains("World"); // true
        
        // 比较
        boolean equals = str.equals("Hello World");    // true
        boolean equalsIgnoreCase = str.equalsIgnoreCase("hello world"); // true
        int compare = str.compareTo("Hello");  // > 0
        
        // 截取
        String sub1 = str.substring(0, 5);  // "Hello"
        String sub2 = str.substring(6);     // "World"
        
        // 替换
        String replace1 = str.replace('o', '0');  // "Hell0 W0rld"
        String replace2 = str.replaceAll("\\s", "_");  // "Hello_World"
        
        // 分割
        String[] parts = str.split(" ");  // ["Hello", "World"]
        
        // 大小写转换
        String upper = str.toUpperCase();  // "HELLO WORLD"
        String lower = str.toLowerCase();  // "hello world"
        
        // 去除空白
        String trimmed = "  abc  ".trim();  // "abc"
    }
}`
			},
			{
				point: 'StringBuilder和StringBuffer用于频繁修改字符串，StringBuilder线程不安全但性能高，StringBuffer线程安全。',
				code: `public class StringBuilderDemo {
    public static void main(String[] args) {
        // StringBuilder（推荐用于单线程）
        StringBuilder sb = new StringBuilder("Hello");
        sb.append(" World");          // 追加
        sb.insert(5, ",");            // 插入
        sb.delete(5, 6);              // 删除
        sb.reverse();                 // 反转
        String result = sb.toString(); // 转为String
        
        // 性能对比
        long start = System.currentTimeMillis();
        
        // String拼接（慢）
        String s = "";
        for (int i = 0; i < 10000; i++) {
            s += i;  // 每次创建新对象
        }
        System.out.println("String耗时: " + (System.currentTimeMillis() - start));
        
        start = System.currentTimeMillis();
        
        // StringBuilder拼接（快）
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 10000; i++) {
            builder.append(i);  // 在原对象上修改
        }
        System.out.println("StringBuilder耗时: " + (System.currentTimeMillis() - start));
        
        // StringBuffer（线程安全）
        StringBuffer buffer = new StringBuffer();
        buffer.append("Thread Safe");
    }
}`
			},
			{
				point: '字符串格式化使用String.format()、System.out.printf()或MessageFormat，支持多种格式化选项。',
				code: `import java.text.MessageFormat;
import java.util.Date;

public class StringFormat {
    public static void main(String[] args) {
        // String.format()
        String name = "张三";
        int age = 25;
        double score = 95.5;
        
        String formatted = String.format("姓名：%s，年龄：%d，分数：%.2f", 
                                         name, age, score);
        System.out.println(formatted);  // 姓名：张三，年龄：25，分数：95.50
        
        // printf()（直接输出）
        System.out.printf("十进制：%d，十六进制：%x，八进制：%o%n", 100, 100, 100);
        System.out.printf("科学计数：%e，百分比：%.2f%%%n", 1234.5, 0.856 * 100);
        
        // 对齐和宽度
        System.out.printf("|%10s|%10s|%n", "姓名", "年龄");
        System.out.printf("|%-10s|%10d|%n", "张三", 25);  // 左对齐
        
        // MessageFormat（国际化）
        String pattern = "在{0}，有{1}个{2}";
        String result = MessageFormat.format(pattern, "北京", 2000, "万人");
        System.out.println(result);  // 在北京，有2000个万人
        
        // 日期格式化
        String dateStr = String.format("当前时间：%tF %tT", new Date(), new Date());
        System.out.println(dateStr);
    }
}`
			}
		]
	},
	{
		id: 12,
		title: '集合框架',
		description: 'Java集合框架提供了List、Set、Map等数据结构，是Java开发中最常用的工具之一。',
		icon: '📚',
		categoryId: 'core',
		categoryName: 'Java核心API',
		categoryIcon: '🔧',
		difficulty: '重要',
		color: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #16a085 0%, #138d75 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #f39c12 0%, #e67e22 100%)',
		keyPoints: [
			{
				point: 'List接口表示有序集合，ArrayList基于数组实现(随机访问快)，LinkedList基于链表实现(插入删除快)。',
				code: `import java.util.*;

public class ListDemo {
    public static void main(String[] args) {
        // ArrayList：动态数组
        List<String> arrayList = new ArrayList<>();
        arrayList.add("Apple");
        arrayList.add("Banana");
        arrayList.add("Cherry");
        arrayList.add(1, "Blueberry");  // 指定位置插入
        
        System.out.println(arrayList.get(0));     // Apple
        arrayList.set(0, "Apricot");              // 修改
        arrayList.remove("Banana");               // 删除
        System.out.println(arrayList.size());     // 大小
        
        // LinkedList：双向链表
        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.addFirst("First");
        linkedList.addLast("Last");
        linkedList.add("Middle");
        
        String first = linkedList.removeFirst();
        String last = linkedList.removeLast();
        
        // 遍历
        for (String item : arrayList) {
            System.out.println(item);
        }
        
        // 性能对比
        // ArrayList：get O(1), add/remove O(n)
        // LinkedList：get O(n), add/remove O(1)
    }
}`
			},
			{
				point: 'Set接口表示无重复元素集合，HashSet基于哈希表(无序)，TreeSet基于红黑树(有序)，LinkedHashSet保持插入顺序。',
				code: `import java.util.*;

public class SetDemo {
    public static void main(String[] args) {
        // HashSet：哈希表，无序，快速查找
        Set<String> hashSet = new HashSet<>();
        hashSet.add("Apple");
        hashSet.add("Banana");
        hashSet.add("Apple");  // 重复元素不会添加
        System.out.println(hashSet.size());  // 2
        
        // TreeSet：红黑树，自动排序
        Set<Integer> treeSet = new TreeSet<>();
        treeSet.add(5);
        treeSet.add(2);
        treeSet.add(8);
        treeSet.add(1);
        System.out.println(treeSet);  // [1, 2, 5, 8]（自动排序）
        
        // LinkedHashSet：保持插入顺序
        Set<String> linkedSet = new LinkedHashSet<>();
        linkedSet.add("C");
        linkedSet.add("A");
        linkedSet.add("B");
        System.out.println(linkedSet);  // [C, A, B]（插入顺序）
        
        // 常用操作
        boolean contains = hashSet.contains("Apple");
        hashSet.remove("Banana");
        hashSet.clear();
    }
}`
			},
			{
				point: 'Map接口存储键值对，HashMap基于哈希表(无序)，TreeMap基于红黑树(按键排序)，LinkedHashMap保持插入顺序。',
				code: `import java.util.*;

public class MapDemo {
    public static void main(String[] args) {
        // HashMap：哈希表，无序，快速查找
        Map<String, Integer> hashMap = new HashMap<>();
        hashMap.put("Alice", 25);
        hashMap.put("Bob", 30);
        hashMap.put("Charlie", 28);
        
        int age = hashMap.get("Alice");          // 25
        boolean hasKey = hashMap.containsKey("Bob");
        boolean hasValue = hashMap.containsValue(30);
        hashMap.remove("Charlie");
        
        // 遍历Map
        for (String key : hashMap.keySet()) {
            System.out.println(key + ": " + hashMap.get(key));
        }
        
        for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
        
        // TreeMap：红黑树，按键排序
        Map<String, Integer> treeMap = new TreeMap<>();
        treeMap.put("C", 3);
        treeMap.put("A", 1);
        treeMap.put("B", 2);
        System.out.println(treeMap);  // {A=1, B=2, C=3}
        
        // LinkedHashMap：保持插入顺序
        Map<String, Integer> linkedMap = new LinkedHashMap<>();
        linkedMap.put("C", 3);
        linkedMap.put("A", 1);
        System.out.println(linkedMap);  // {C=3, A=1}
    }
}`
			},
			{
				point: 'Collections工具类提供了排序、查找、同步、不可修改等集合操作方法。',
				code: `import java.util.*;

public class CollectionsDemo {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 9));
        
        // 排序
        Collections.sort(list);                    // [1, 2, 5, 8, 9]
        Collections.reverse(list);                 // [9, 8, 5, 2, 1]
        
        // 查找
        int max = Collections.max(list);           // 9
        int min = Collections.min(list);           // 1
        int index = Collections.binarySearch(list, 5);  // 需要先排序
        
        // 替换
        Collections.fill(list, 0);                 // 全部替换为0
        Collections.replaceAll(list, 0, 1);        // 替换所有0为1
        
        // 打乱
        Collections.shuffle(list);                 // 随机打乱
        
        // 旋转
        Collections.rotate(list, 2);               // 向右旋转2位
        
        // 不可修改集合
        List<Integer> unmodifiable = Collections.unmodifiableList(list);
        // unmodifiable.add(10);  // UnsupportedOperationException
        
        // 同步集合（线程安全）
        List<Integer> syncList = Collections.synchronizedList(new ArrayList<>());
        
        // 单例集合
        Set<String> singleton = Collections.singleton("only");
        
        // 空集合
        List<String> empty = Collections.emptyList();
    }
}`
			},
			{
				point: '泛型确保类型安全，避免类型转换，编译时检查类型错误，使用<>指定类型参数。',
				code: `import java.util.*;

public class GenericsDemo {
    public static void main(String[] args) {
        // 不使用泛型（不推荐）
        List list1 = new ArrayList();
        list1.add("String");
        list1.add(100);
        String s = (String) list1.get(1);  // 运行时异常！
        
        // 使用泛型（推荐）
        List<String> list2 = new ArrayList<>();
        list2.add("String");
        // list2.add(100);  // 编译错误！类型不匹配
        String s2 = list2.get(0);  // 无需类型转换
        
        // 泛型方法
        String[] names = {"Alice", "Bob", "Charlie"};
        List<String> nameList = arrayToList(names);
        
        // 通配符
        List<? extends Number> numbers = new ArrayList<Integer>();
        // numbers.add(10);  // 错误！不能添加
        Number num = numbers.get(0);  // 可以读取
        
        // 多个类型参数
        Map<String, Integer> map = new HashMap<>();
        map.put("age", 25);
    }
    
    // 泛型方法
    public static <T> List<T> arrayToList(T[] array) {
        List<T> list = new ArrayList<>();
        for (T item : array) {
            list.add(item);
        }
        return list;
    }
}`
			}
		]
	},
	{
		id: 13,
		title: '异常处理',
		description: '异常处理机制用于处理程序运行中的错误，提高程序的健壮性和可维护性。',
		icon: '⚠️',
		categoryId: 'core',
		categoryName: 'Java核心API',
		categoryIcon: '🔧',
		difficulty: '重要',
		color: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #16a085 0%, #138d75 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #f39c12 0%, #e67e22 100%)',
		keyPoints: [
			{
				point: 'Java异常分为检查异常(必须处理)和运行时异常(可选处理)，所有异常继承自Throwable。',
				code: `// 异常层次结构
// Throwable
//  ├── Error（系统错误，不需要捕获）
//  │   ├── OutOfMemoryError
//  │   └── StackOverflowError
//  └── Exception
//      ├── IOException（检查异常）
//      ├── SQLException（检查异常）
//      └── RuntimeException（运行时异常）
//          ├── NullPointerException
//          ├── ArrayIndexOutOfBoundsException
//          └── ArithmeticException

public class ExceptionDemo {
    // 检查异常：必须处理
    public void readFile() throws IOException {
        FileReader reader = new FileReader("file.txt");
        // 必须try-catch或throws
    }
    
    // 运行时异常：可以不处理
    public int divide(int a, int b) {
        return a / b;  // 可能抛出ArithmeticException
    }
}`
			},
			{
				point: 'try-catch-finally用于捕获和处理异常，finally块总是执行，常用于资源清理。',
				code: `public class TryCatchDemo {
    public void example1() {
        try {
            int result = 10 / 0;  // 可能抛出异常
            System.out.println("正常执行");
        } catch (ArithmeticException e) {
            System.out.println("捕获到算术异常: " + e.getMessage());
            e.printStackTrace();  // 打印堆栈信息
        } finally {
            System.out.println("finally块总是执行");
        }
    }
    
    // 多个catch块
    public void example2() {
        try {
            String str = null;
            System.out.println(str.length());
            int[] arr = new int[5];
            System.out.println(arr[10]);
        } catch (NullPointerException e) {
            System.out.println("空指针异常");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("数组越界异常");
        } catch (Exception e) {
            System.out.println("其他异常");  // 放在最后
        }
    }
    
    // try-with-resources（Java 7+）
    public void example3() {
        try (FileReader reader = new FileReader("file.txt");
             BufferedReader br = new BufferedReader(reader)) {
            String line = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }  // 自动关闭资源，无需finally
    }
}`
			},
			{
				point: 'throw用于抛出异常对象，throws声明方法可能抛出的异常，调用方必须处理或继续声明。',
				code: `public class ThrowDemo {
    // throws声明异常
    public void method1() throws IOException, SQLException {
        if (someCondition) {
            throw new IOException("IO错误");
        }
        if (otherCondition) {
            throw new SQLException("数据库错误");
        }
    }
    
    // 调用方必须处理
    public void method2() {
        try {
            method1();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    // 或继续声明
    public void method3() throws IOException, SQLException {
        method1();
    }
    
    // 验证参数
    public void setAge(int age) {
        if (age < 0 || age > 150) {
            throw new IllegalArgumentException("年龄必须在0-150之间");
        }
        this.age = age;
    }
    
    // 业务异常
    public void withdraw(double amount) {
        if (amount > balance) {
            throw new InsufficientFundsException("余额不足");
        }
        balance -= amount;
    }
}`
			},
			{
				point: '自定义异常继承Exception(检查异常)或RuntimeException(运行时异常)，提供有意义的错误信息。',
				code: `// 自定义检查异常
public class InsufficientFundsException extends Exception {
    private double amount;
    
    public InsufficientFundsException(String message) {
        super(message);
    }
    
    public InsufficientFundsException(String message, double amount) {
        super(message);
        this.amount = amount;
    }
    
    public double getAmount() {
        return amount;
    }
}

// 自定义运行时异常
public class BusinessException extends RuntimeException {
    private int errorCode;
    
    public BusinessException(int errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }
    
    public int getErrorCode() {
        return errorCode;
    }
}

// 使用自定义异常
public class BankAccount {
    public void withdraw(double amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException("余额不足", amount - balance);
        }
        balance -= amount;
    }
}`
			},
			{
				point: '异常处理最佳实践：不要捕获所有异常、及时释放资源、提供有意义的错误信息、不要忽略异常。',
				code: `public class ExceptionBestPractices {
    // ❌ 不好的做法
    public void badPractice1() {
        try {
            // 业务代码
        } catch (Exception e) {
            // 什么都不做，吞掉异常
        }
    }
    
    public void badPractice2() throws Exception {
        // 抛出笼统的Exception
        throw new Exception("error");
    }
    
    // ✅ 好的做法
    public void goodPractice1() {
        try {
            processFile();
        } catch (IOException e) {
            logger.error("文件处理失败: " + e.getMessage(), e);
            // 处理异常或重新抛出
            throw new BusinessException("文件处理失败", e);
        }
    }
    
    public void goodPractice2() {
        Connection conn = null;
        try {
            conn = getConnection();
            // 使用连接
        } catch (SQLException e) {
            logger.error("数据库操作失败", e);
        } finally {
            // 确保资源释放
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    logger.error("关闭连接失败", e);
                }
            }
        }
    }
    
    // 使用try-with-resources更优雅
    public void goodPractice3() throws IOException {
        try (FileInputStream fis = new FileInputStream("file.txt")) {
            // 使用资源
        }  // 自动关闭
    }
}`
			}
		]
	},
	{
		id: 14,
		title: 'IO流',
		description: 'Java IO提供了文件读写、网络通信等功能，分为字节流和字符流，理解流的分类和使用场景。',
		icon: '📂',
		categoryId: 'core',
		categoryName: 'Java核心API',
		categoryIcon: '🔧',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #16a085 0%, #138d75 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: 'Java IO分为字节流(InputStream/OutputStream)和字符流(Reader/Writer)，字节流处理二进制数据，字符流处理文本数据。',
				code: `import java.io.*;

public class IODemo {
    // 字节流：读取文件
    public void byteStreamRead() throws IOException {
        try (FileInputStream fis = new FileInputStream("data.bin")) {
            int data;
            while ((data = fis.read()) != -1) {
                System.out.print((char) data);
            }
        }
    }
    
    // 字节流：写入文件
    public void byteStreamWrite() throws IOException {
        try (FileOutputStream fos = new FileOutputStream("output.bin")) {
            String content = "Hello World";
            fos.write(content.getBytes());
        }
    }
    
    // 字符流：读取文件
    public void charStreamRead() throws IOException {
        try (FileReader fr = new FileReader("text.txt");
             BufferedReader br = new BufferedReader(fr)) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
    
    // 字符流：写入文件
    public void charStreamWrite() throws IOException {
        try (FileWriter fw = new FileWriter("output.txt");
             BufferedWriter bw = new BufferedWriter(fw)) {
            bw.write("第一行\n");
            bw.write("第二行\n");
        }
    }
}`
			},
			{
				point: '缓冲流(BufferedInputStream/BufferedReader)提供缓冲功能，大幅提高IO性能，适用于频繁读写场景。',
				code: `import java.io.*;

public class BufferedStreamDemo {
    // 使用缓冲流提高性能
    public void copyFile(String src, String dest) throws IOException {
        try (BufferedInputStream bis = new BufferedInputStream(
                 new FileInputStream(src));
             BufferedOutputStream bos = new BufferedOutputStream(
                 new FileOutputStream(dest))) {
            
            byte[] buffer = new byte[8192];  // 8KB缓冲区
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
        }
    }
    
    // 按行读取文本文件
    public void readTextFile(String filename) throws IOException {
        try (BufferedReader br = new BufferedReader(
                 new FileReader(filename))) {
            String line;
            int lineNumber = 1;
            while ((line = br.readLine()) != null) {
                System.out.println(lineNumber++ + ": " + line);
            }
        }
    }
    
    // 写入文本文件
    public void writeTextFile(String filename, List<String> lines) 
            throws IOException {
        try (BufferedWriter bw = new BufferedWriter(
                 new FileWriter(filename))) {
            for (String line : lines) {
                bw.write(line);
                bw.newLine();  // 写入换行符
            }
        }
    }
}`
			},
			{
				point: '对象流(ObjectInputStream/ObjectOutputStream)用于序列化和反序列化对象，类需要实现Serializable接口。',
				code: `import java.io.*;

// 可序列化的类
public class Person implements Serializable {
    private static final long serialVersionUID = 1L;  // 版本号
    
    private String name;
    private int age;
    private transient String password;  // transient字段不序列化
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class ObjectStreamDemo {
    // 序列化：将对象写入文件
    public void serialize(Person person, String filename) 
            throws IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(
                 new FileOutputStream(filename))) {
            oos.writeObject(person);
        }
    }
    
    // 反序列化：从文件读取对象
    public Person deserialize(String filename) 
            throws IOException, ClassNotFoundException {
        try (ObjectInputStream ois = new ObjectInputStream(
                 new FileInputStream(filename))) {
            return (Person) ois.readObject();
        }
    }
    
    public static void main(String[] args) throws Exception {
        ObjectStreamDemo demo = new ObjectStreamDemo();
        
        Person person = new Person("张三", 25);
        demo.serialize(person, "person.dat");
        
        Person loadedPerson = demo.deserialize("person.dat");
        System.out.println(loadedPerson.getName());  // 张三
    }
}`
			},
			{
				point: 'File类用于文件和目录操作，提供创建、删除、重命名、遍历等功能。',
				code: `import java.io.*;

public class FileDemo {
    public void fileOperations() {
        // 创建File对象
        File file = new File("test.txt");
        File dir = new File("mydir");
        
        // 文件信息
        boolean exists = file.exists();
        boolean isFile = file.isFile();
        boolean isDir = file.isDirectory();
        long size = file.length();
        String name = file.getName();
        String path = file.getAbsolutePath();
        
        // 文件操作
        try {
            boolean created = file.createNewFile();  // 创建文件
            boolean deleted = file.delete();          // 删除
            boolean renamed = file.renameTo(new File("new.txt"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // 目录操作
        boolean dirCreated = dir.mkdir();        // 创建目录
        boolean dirsCreated = dir.mkdirs();      // 创建多级目录
        
        // 遍历目录
        File directory = new File(".");
        String[] files = directory.list();       // 文件名列表
        File[] fileObjects = directory.listFiles();  // File对象列表
        
        // 递归遍历
        listFiles(directory, 0);
    }
    
    // 递归遍历目录
    public void listFiles(File dir, int depth) {
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                System.out.println("  ".repeat(depth) + file.getName());
                if (file.isDirectory()) {
                    listFiles(file, depth + 1);
                }
            }
        }
    }
}`
			},
			{
				point: 'NIO(New IO)提供更高效的IO操作，包括Channel、Buffer、Selector等，适用于高性能场景。',
				code: `import java.nio.*;
import java.nio.channels.*;
import java.nio.file.*;

public class NIODemo {
    // 使用NIO复制文件
    public void copyFileNIO(String src, String dest) throws IOException {
        try (FileChannel sourceChannel = FileChannel.open(
                 Paths.get(src), StandardOpenOption.READ);
             FileChannel destChannel = FileChannel.open(
                 Paths.get(dest), 
                 StandardOpenOption.WRITE, 
                 StandardOpenOption.CREATE)) {
            
            sourceChannel.transferTo(0, sourceChannel.size(), destChannel);
        }
    }
    
    // 使用Buffer读取文件
    public void readFileNIO(String filename) throws IOException {
        try (FileChannel channel = FileChannel.open(
                 Paths.get(filename), StandardOpenOption.READ)) {
            
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (channel.read(buffer) > 0) {
                buffer.flip();  // 切换到读模式
                while (buffer.hasRemaining()) {
                    System.out.print((char) buffer.get());
                }
                buffer.clear();  // 清空缓冲区
            }
        }
    }
    
    // 使用Path和Files工具类
    public void filesUtility() throws IOException {
        Path path = Paths.get("test.txt");
        
        // 读取所有行
        List<String> lines = Files.readAllLines(path);
        
        // 写入所有行
        List<String> content = Arrays.asList("Line 1", "Line 2");
        Files.write(path, content);
        
        // 复制文件
        Files.copy(path, Paths.get("copy.txt"), 
                   StandardCopyOption.REPLACE_EXISTING);
        
        // 删除文件
        Files.delete(path);
    }
}`
			}
		]
	},
	{
		id: 15,
		title: '日期时间API',
		description: 'Java 8引入了新的日期时间API，提供了更加清晰、不可变、线程安全的日期时间处理方式。',
		icon: '📅',
		categoryId: 'core',
		categoryName: 'Java核心API',
		categoryIcon: '🔧',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #16a085 0%, #138d75 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: 'LocalDate、LocalTime、LocalDateTime表示本地日期、时间和日期时间，不包含时区信息。',
				code: `import java.time.*;

public class LocalDateTimeDemo {
    public void example() {
        // LocalDate：日期
        LocalDate today = LocalDate.now();
        LocalDate birthday = LocalDate.of(1990, 5, 15);
        LocalDate parsed = LocalDate.parse("2023-12-25");
        
        System.out.println("今天: " + today);
        System.out.println("年: " + today.getYear());
        System.out.println("月: " + today.getMonthValue());
        System.out.println("日: " + today.getDayOfMonth());
        System.out.println("星期: " + today.getDayOfWeek());
        
        // LocalTime：时间
        LocalTime now = LocalTime.now();
        LocalTime time = LocalTime.of(14, 30, 0);
        
        System.out.println("当前时间: " + now);
        System.out.println("时: " + now.getHour());
        System.out.println("分: " + now.getMinute());
        
        // LocalDateTime：日期+时间
        LocalDateTime dateTime = LocalDateTime.now();
        LocalDateTime specific = LocalDateTime.of(2023, 12, 25, 14, 30);
        
        System.out.println("日期时间: " + dateTime);
    }
}`
			},
			{
				point: '日期时间的计算和比较：plus、minus、with方法用于加减和设置，isBefore、isAfter用于比较。',
				code: `import java.time.*;

public class DateCalculation {
    public void example() {
        LocalDate today = LocalDate.now();
        
        // 加减操作
        LocalDate tomorrow = today.plusDays(1);
        LocalDate nextWeek = today.plusWeeks(1);
        LocalDate nextMonth = today.plusMonths(1);
        LocalDate nextYear = today.plusYears(1);
        
        LocalDate yesterday = today.minusDays(1);
        LocalDate lastMonth = today.minusMonths(1);
        
        // 使用Period
        Period period = Period.ofDays(10);
        LocalDate future = today.plus(period);
        
        // with方法：设置特定字段
        LocalDate firstDay = today.withDayOfMonth(1);
        LocalDate newYear = today.withMonth(1).withDayOfMonth(1);
        
        // 比较
        boolean isBefore = today.isBefore(tomorrow);
        boolean isAfter = today.isAfter(yesterday);
        boolean isEqual = today.isEqual(LocalDate.now());
        
        // 计算时间差
        Period diff = Period.between(birthday, today);
        System.out.println("年龄: " + diff.getYears() + "岁");
        
        long days = ChronoUnit.DAYS.between(birthday, today);
        System.out.println("已过" + days + "天");
    }
}`
			},
			{
				point: 'ZonedDateTime处理带时区的日期时间，Instant表示时间戳，适用于记录事件发生时间。',
				code: `import java.time.*;

public class ZonedDateTimeDemo {
    public void example() {
        // ZonedDateTime：带时区的日期时间
        ZonedDateTime now = ZonedDateTime.now();
        ZonedDateTime tokyo = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
        ZonedDateTime ny = ZonedDateTime.now(ZoneId.of("America/New_York"));
        
        System.out.println("北京时间: " + now);
        System.out.println("东京时间: " + tokyo);
        System.out.println("纽约时间: " + ny);
        
        // 时区转换
        ZonedDateTime tokyoTime = now.withZoneSameInstant(
            ZoneId.of("Asia/Tokyo"));
        
        // Instant：时间戳（UTC）
        Instant instant = Instant.now();
        long epochSecond = instant.getEpochSecond();
        long epochMilli = instant.toEpochMilli();
        
        System.out.println("时间戳: " + instant);
        System.out.println("秒: " + epochSecond);
        System.out.println("毫秒: " + epochMilli);
        
        // Instant与ZonedDateTime转换
        ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
        Instant inst = zdt.toInstant();
    }
}`
			},
			{
				point: 'DateTimeFormatter用于日期时间的格式化和解析，支持自定义格式和本地化。',
				code: `import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class FormatterDemo {
    public void example() {
        LocalDateTime now = LocalDateTime.now();
        
        // 预定义格式
        String iso = now.format(DateTimeFormatter.ISO_DATE_TIME);
        String basic = now.format(DateTimeFormatter.BASIC_ISO_DATE);
        
        // 自定义格式
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formatted1 = now.format(formatter1);
        System.out.println(formatted1);  // 2023-12-25 14:30:00
        
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分");
        String formatted2 = now.format(formatter2);
        System.out.println(formatted2);  // 2023年12月25日 14时30分
        
        // 本地化格式
        DateTimeFormatter usFormatter = DateTimeFormatter
            .ofLocalizedDateTime(FormatStyle.FULL)
            .withLocale(Locale.US);
        String usFormat = now.format(usFormatter);
        
        // 解析字符串
        String dateStr = "2023-12-25 14:30:00";
        LocalDateTime parsed = LocalDateTime.parse(dateStr, formatter1);
        
        // 解析日期
        String dateStr2 = "2023-12-25";
        LocalDate date = LocalDate.parse(dateStr2);
    }
}`
			},
			{
				point: 'Period表示日期间隔(年月日)，Duration表示时间间隔(时分秒)，用于计算时间差。',
				code: `import java.time.*;

public class PeriodDurationDemo {
    public void example() {
        // Period：日期间隔
        LocalDate start = LocalDate.of(2020, 1, 1);
        LocalDate end = LocalDate.of(2023, 12, 25);
        
        Period period = Period.between(start, end);
        System.out.println("相差: " + period.getYears() + "年" +
                          period.getMonths() + "月" +
                          period.getDays() + "天");
        
        // 创建Period
        Period oneYear = Period.ofYears(1);
        Period twoMonths = Period.ofMonths(2);
        Period tenDays = Period.ofDays(10);
        Period complex = Period.of(1, 2, 10);  // 1年2月10天
        
        LocalDate future = start.plus(complex);
        
        // Duration：时间间隔
        LocalTime startTime = LocalTime.of(9, 0);
        LocalTime endTime = LocalTime.of(17, 30);
        
        Duration duration = Duration.between(startTime, endTime);
        System.out.println("工作时长: " + duration.toHours() + "小时" +
                          duration.toMinutesPart() + "分钟");
        
        // 创建Duration
        Duration oneHour = Duration.ofHours(1);
        Duration thirtyMins = Duration.ofMinutes(30);
        Duration fiveSeconds = Duration.ofSeconds(5);
        
        LocalTime later = startTime.plus(oneHour);
    }
}`
			}
		]
	}
];